/*

    tools23d - tools for converting images to 3D formats.
    Copyright (C) 2014  Dave Gorst

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/


/**
 * @file   readml.c
 * @brief  Functions used to read multiline input from a text buffer.
 *
 */

#include <stdio.h>

#include "tools23d.h"
#include "readml.h"

#define MAX_LINE_LENGTH 509

static char * current_pos;

/**
Retrieve the first line from string input buffer.

@param	output_buffer	Buffer to write line to.
@param	input_lines		Input lines.
@return	Return code indicating result.
*/

readml_return T3D_GetFirstLine (char * output_buffer, char * input_lines)
{
	current_pos = input_lines;

	return T3D_GetNextLine (output_buffer);
}


/**
Retrieve subsequent line from string input buffer.

@param	output_buffer	Buffer to write line to.
@return	Return code indicating result.
*/

readml_return T3D_GetNextLine (char * output_buffer)
{
	char * lb_pointer = output_buffer;
	char * endpoint = lb_pointer + MAX_LINE_LENGTH;

	readml_return retcode;

	while ((*current_pos != '\n') && (*current_pos != '\0') && (current_pos != endpoint))
	{
		*lb_pointer++ = *current_pos++;
	}

	*lb_pointer = '\0';

	if (current_pos == endpoint)
		retcode = readml_error;
	else if (*current_pos == '\0')
		retcode = readml_no_more_lines;
	else if (*(current_pos+1) == '\n')
		retcode = readml_blank_line;
	else
		retcode = readml_success;

	current_pos++;

	return retcode;
}
